package com.xh.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.xh.core.bean.AjaxResult;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.constant.XhMsgConstant;
import com.xh.core.exception.XhException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;

import static org.springframework.http.HttpStatus.NOT_EXTENDED;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/8/10 08:05
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private boolean isAnsynJsonRequest(HttpServletRequest request){
        System.out.println(request.getHeader("x-requested-with"));
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { //如果是ajax请求响应头会有x-requested-with
            return true;
        }
        return false;
    }

    /**
     * 在controller里面内容执行之前，校验一些参数不匹配啊，Get post方法不对啊之类的
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>(ex.getMessage(), NOT_EXTENDED);
    }


    /**
     * 所有异常报错
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    public AjaxResult allExceptionHandler(HttpServletRequest request, HttpServletResponse response,
                                            Exception exception) throws Exception
    {
        AjaxResult json=new AjaxResult(AjaxResultConstant.Result.ERROR, -1, XhMsgConstant.SYSTEM_ERROR_MSG);
        if(exception instanceof HttpMediaTypeNotAcceptableException){

        }else{
            String errorMsg;
            if(exception instanceof XhException){
                errorMsg=exception.getMessage();
            }else if(exception instanceof BindException){
                errorMsg="";
                BindException be=(BindException)exception;
                for(int i=0;i<be.getAllErrors().size();i++){
                    if(i>0){
                        errorMsg+="<br/>";
                    }
                    errorMsg+=be.getAllErrors().get(i).getDefaultMessage();
                    if(i==4){
                        break;
                    }
                }
                if(be.getAllErrors().size()>5){
                    errorMsg+="等"+be.getAllErrors().size()+"个错误";
                }
            }else{
                errorMsg= XhMsgConstant.SYSTEM_ERROR_MSG;
                log.error("系统异常",exception);
            }
//            if(isAnsynJsonRequest(request)){
           /*  使用response返回    */
                //response.setStatus(9000); //设置状态码
                //response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
                //response.setCharacterEncoding("UTF-8"); //避免乱码
                //response.setHeader("Cache-Control", "no-cache, must-revalidate");
                String token=UUID.randomUUID().toString();
                //request.getSession(false).setAttribute("token", token);
                //response.setHeader("REQUEST_TOKEN", token);
                json=new AjaxResult(AjaxResultConstant.Result.ERROR, errorMsg);
//            }
        }
            return json;
    }

    public String getExceptionAllInfo(Exception ex) {
        ByteArrayOutputStream out = null;
        PrintStream pout = null;
        String ret = "";
        try {
            out = new ByteArrayOutputStream();
            pout = new PrintStream(out);
            ex.printStackTrace(pout);
            ret = new String(out.toByteArray());
            out.close();
        }catch(Exception e){
            return ex.getMessage();
        }finally{
            if(pout!=null){
                pout.close();
            }
        }
        return ret;

    }

}